<template>
    <div class="login-container">
      <vue-particles
      class="particles-bg"
      color="#ffffff"
      :particleOpacity="0.6"
      :particlesNumber="600"
      shapeType="circle"
      :particleSize="4"
      :linesWidth="1"
      :lineLinked="true"
      :moveSpeed="3"
      :hoverEffect="true"
      hoverMode="repulse"
    />
    <div class="login-box">
      <div class="login-header">
        <h1>在线教育考试平台</h1>
        <p>欢迎登录系统</p>
      </div>
        
        <el-form class="login-form" :model="loginForm" :rules="loginRules" ref="loginForm">
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入登录账号"
              prefix-icon="el-icon-user"
            ></el-input>
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入登录密码"
              prefix-icon="el-icon-lock"
              show-password
            ></el-input>
          </el-form-item>

          <el-form-item prop="captcha">
  <div class="captcha-container">
    <el-input
      v-model="loginForm.captcha"
      placeholder="请输入验证码"
      prefix-icon="el-icon-key"
      class="captcha-input"
    ></el-input>
    <div class="captcha-code" @click="refreshCaptcha">
      {{ captchaText }}
    </div>
  </div>
</el-form-item>
          
          <el-form-item>
            <div class="remember-me">
              <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
              :loading="loading"
            >登录</el-button>
          </el-form-item>
        </el-form>
      
      </div>
    </div>
  </template>
  
  <script>
import VueParticles from 'vue-particles/src/vue-particles/vue-particles'

 export default {
  components: {
    VueParticles
  },
  name: 'LoginView',
  data() {
    // 验证码验证规则
    const validateCaptcha = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入验证码'));
      } else if (value.toLowerCase() !== this.captchaText.toLowerCase()) {
        callback(new Error('验证码不正确'));
        this.refreshCaptcha();
      } else {
        callback();
      }
    };
    
    return {
      loading: false,
      captchaText: '',
      loginForm: {
        username: '',
        password: '',
        captcha: '',
        remember: false
      },
      loginRules: {
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' }
        ],
        captcha: [
          { validator: validateCaptcha, trigger: 'blur' }
        ]
      },
      // 正确的账号密码（实际项目中应该从API获取）
      correctCredentials: {
        username: '张三',
        password: '123456'
      }
    };
  },

  mounted() {
  // 添加鼠标轨迹效果
  document.addEventListener('mousemove', this.createCursorEffect);
  this.refreshCaptcha();
},
  
    methods: {
      // 生成随机验证码
      generateCaptcha() {
        const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        let captcha = '';
        for (let i = 0; i < 4; i++) {
          captcha += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return captcha;
      },
      
      // 刷新验证码
      refreshCaptcha() {
  this.captchaText = this.generateCaptcha();
  
  // 添加nextTick确保DOM更新完成
  this.$nextTick(() => {
    const captchaEl = document.querySelector('.captcha-code');
    if (captchaEl) { // 添加空值检查
      captchaEl.style.transform = 'scale(0.9)';
      setTimeout(() => {
        captchaEl.style.transform = 'scale(1)';
      }, 200);
    }
  });
},
      
      // 处理登录
      handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          
          // 模拟API验证过程
          setTimeout(() => {
            this.loading = false;
            
            // 验证账号密码和验证码
            if (
              this.loginForm.username === this.correctCredentials.username &&
              this.loginForm.password === this.correctCredentials.password &&
              this.loginForm.captcha.toLowerCase() === this.captchaText.toLowerCase()
            ) {
              // 验证通过
              this.$message.success('登录成功');
              this.$router.push('/main');
              
              // 如果勾选了记住密码，保存到localStorage
              if (this.loginForm.remember) {
                localStorage.setItem('rememberedUser', JSON.stringify({
                  username: this.loginForm.username,
                  password: this.loginForm.password
                }));
              }
            } else {
              // 验证失败
              this.$message.error('账号或密码错误');
              this.refreshCaptcha(); // 刷新验证码
              this.loginForm.captcha = ''; // 清空验证码输入框
            }
          }, 1500);
        } else {
          // 表单验证失败
          this.$message.error('请填写正确的登录信息');
          return false;
        }
      });
    },
    createCursorEffect(e) {
    const effect = document.createElement('div');
    effect.className = 'cursor-effect';
    effect.style.left = e.clientX + 'px';
    effect.style.top = e.clientY + 'px';
    document.body.appendChild(effect);
    
    setTimeout(() => {
      effect.remove();
    }, 1000);
  }
  },
  created() {
    
    // 检查是否有记住的账号密码
    const rememberedUser = localStorage.getItem('rememberedUser');
    if (rememberedUser) {
      try {
        const user = JSON.parse(rememberedUser);
        this.loginForm.username = user.username;
        this.loginForm.password = user.password;
        this.loginForm.remember = true;
      } catch (e) {
        console.error('读取记住的账号失败', e);
      }
    }
  }
};
  </script>
  
  <style scoped>
.particles-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #a52273 30%, #3498db 100%);
}

.login-container {
  position: relative;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  position: relative;
  z-index: 1;
  width: 420px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.92);
  border-radius: 12px;
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.18);
  backdrop-filter: blur(8px);
  animation: slideUp 0.6s cubic-bezier(0.23, 1, 0.32, 1);
}

.login-header {
  text-align: center;
  margin-bottom: 35px;
}

.login-header h1 {
  font-size: 26px;
  color: #2c3e50;
  margin-bottom: 8px;
  letter-spacing: 1.5px;
}

.login-header p {
  font-size: 15px;
  color: #7f8c8d;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  letter-spacing: 1.2px;
  background: linear-gradient(45deg, #3498db, #2980b9);
  border: none;
  transition: all 0.3s ease;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 20px rgba(52, 152, 219, 0.3);
}

.captcha-container {
  display: flex;
  gap: 10px; /* 添加间距 */
  width: 100%;
}

.captcha-input {
  flex: 1; 
  margin-right: 0; 
}

.captcha-code {
  width: 120px; 
  height: 40px;
  flex-shrink: 0; 
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #486481 0%, #e9ecef 100%);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-family: 'Arial', sans-serif; /* 使用等宽字体 */
  font-weight: 600;
  color: #2c3e50;
  border: 1px solid #ced4da;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .captcha-container {
    flex-direction: column;
  }
  
  .captcha-code {
    width: 100%;
    height: 45px;
  }
}

.remember-me {
  display: flex;
  width: 100%;
  margin: 10px;
  justify-content: flex-start;
}
  </style>